package com.itheima.filter;
import com.itheima.utils.CookieUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "loginFilter", urlPatterns = "/*")  // /*表示全部拦截
public class AuthFilter implements Filter, Ordered {

    @Value("${sign}")
    private String sign;


    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求响应对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //CROS复杂请求时会首先发送一个OPTIONS请求做嗅探，来测试服务器是否支持本次请求，请求成功后才会发送真实的请求；
        // 而OPTIONS请求不会携带数据，导致这个请求被拦截了，直接返回了状态码，响应头中没携带解决跨域问题的头部信息，出现了跨域问题。
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            filterChain.doFilter(request, response);
            return;
        }
        String uri = request.getRequestURI();
        if (uri.contains("/auth/login")||uri.contains("/auth/register") ||uri.contains("/creatCode/validCode")
                ||uri.contains(".css")||uri.contains("/index.html")||uri.contains("/favicon.ico")
                ||uri.contains(".js")||uri.contains(".md")||uri.contains(".json")
                ||uri.contains(".gif")||uri.contains(".png")||uri.contains(".jpg")) {
            filterChain.doFilter(request, response);
            return;
        }
        //2. 不是登录请求, 且请求中没有携带token , 则拒绝访问
        //2.1 获取请求中的cookie
        String token = CookieUtils.getCookieValue(request,"token");
        //2.2 判断是否携带cookie
        if (StringUtils.isEmpty(token)) {
           //异常解析器,可以将异常传入全局异常处理器中
            resolver.resolveException(request,response,null,new RuntimeException("token无效或过期!"));
            return;
        }

        try {
            //校验token
            Claims claims = Jwts.parser().setSigningKey(sign).parseClaimsJws(token).getBody();
            //放行
            filterChain.doFilter(request,response);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            //异常解析器,可以将异常传入全局异常处理器中
            resolver.resolveException(request,response,null,new RuntimeException("token无效或过期!"));
            return;
        }
    }


    /**
     * 从cookie中获取token
     *
     * @param request
     * @return
     */
    private String getJtiFromCookies(HttpServletRequest request) {
        //1.获取cookie对象
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 1;
    }


}
